<?php

namespace App\Http\Controllers\Backend;

use App\Exceptions\HttpResponseException;
use App\Traits\WebResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\SortRequest;
use Illuminate\Http\JsonResponse;

class BaseController extends Controller
{
    use WebResponse;

    /**
     * 服务
     * @var object $service
     */
    protected $service;

    /**
     * 公共删除方法
     * @return JsonResponse
     */
    public function delete() : JsonResponse
    {
        return $this->formSubmission(request()->input(), function ($data) {
            $this->service->deleteHandle($data)->delete()->deleteAfter();
        });
    }

    /**
     * 公共排序方法
     * @param SortRequest $request
     * @return JsonResponse
     */
    public function sort(SortRequest $request) : JsonResponse
    {
        return $this->formSubmission($request->input('data', []), function ($data) {
            $this->service->sort($data)->sortAfter();
        });
    }

    /**
     * 保护系统批量删除
     * @return string
     */
    public function deletes()
    {
        return $this->formSubmission(request()->input(), function ($data) {
            $this->service->deletesHandle($data)->deletes()->deletesAfter();
        });
    }

    /**
     * 表单新增和删除操作
     * @param array $request_data
     * @param array $success_data
     * @param $method
     * @return JsonResponse
     */
    protected function formSubmission(array $request_data, $method, array $success_data = []) : JsonResponse
    {
        try {
            $method($request_data);
            return $this->success($success_data);

        } catch (HttpResponseException $e) {
            return $this->failed($e->getMessage(), $e->getCode());
        }
    }
}
